package top.fengyulou.common;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Web工具
 */
public class WebUtils {
    /**
     * 获取Cookie
     *
     * @param request
     * @param key
     * @return
     */
    public static String getCookie(HttpServletRequest request, String key) {
        Cookie[] cookies = request.getCookies();
        if (ObjectUtils.isNotEmpty(cookies)) {
            for (int i = 0; i < cookies.length; i++) {
                if (key.equals(cookies[i].getName())) {
                    return cookies[i].getValue();
                }
            }
        }
        return null;
    }

    /**
     * 设置Cookie
     *
     * @param response
     * @param key
     * @param value
     */
    public static void setCookie(HttpServletResponse response, String key, String value) {
        if (StringUtils.isNotBlank(key) && StringUtils.isNotBlank(value)) {
            Cookie cookie = new Cookie(key, value);
            cookie.setMaxAge(60 * 30);
            cookie.setPath("/");
            response.addCookie(cookie);
        }
    }

    /**
     * 重定向地址
     *
     * @param dname 域名
     * @param uri   连接
     * @return
     */
    public static String redirect(String dname, String uri) {
        return new StringBuilder("redirect:").append(dname).append(uri).toString();
    }

    /**
     * 判断是否是ajax请求
     *
     * @param request
     * @return
     */
    public static boolean isAjax(HttpServletRequest request) {
        return (request.getHeader("X-Requested-With") != null && "XMLHttpRequest".equals(request.getHeader("X-Requested-With")));
    }
}
